package cn.yangliu.tools;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.java.Log;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * the type of com-tool
 *
 * <p>
 * .
 *
 * @author 杨柳
 * @date 2021-09-30
 */
@Log
@Component
public class ExcelReadHandler extends AnalysisEventListener<Command> {

    /**
     * 临时缓存
     */
    private Map<String, String> commandMap;

    /**
     * 读取xlsx文件 得到键值对
     *
     * @param file 文件绝对路径
     * @param sheet sheet名
     * @return 指令键值对
     */
    public Map<String, String> read(String file, String sheet){
        Resource resource = new FileSystemResource(file);
        try (InputStream is = resource.getInputStream()){
            EasyExcelFactory.read(is, Command.class, this).sheet(sheet).doRead();
        }catch (Exception e) {
            throw new UnsupportedOperationException(e);
        }
        Map<String, String> dataMap = new HashMap<>(commandMap);
        commandMap = null;
        return dataMap;
    }

    /**
     * 读取过程处理
     *
     * @param data 数据行
     * @param context 上下文
     */
    @Override
    public void invoke(Command data, AnalysisContext context) {
        if (Objects.isNull(commandMap)) {
            commandMap = new HashMap<>();
        }
        commandMap.put(data.getReceive(), data.getSend());
    }

    /**
     * 读取完成
     *
     * @param context 上下文
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("读取完成...");
    }

}

